package com.example.lotterysystem.common.utils;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;

import java.util.List;
import java.util.concurrent.Callable;


public class JacksonUtil {
    /**
     * 单例
     */
    private final static ObjectMapper OBJECT_MAPPER;

    static {
        OBJECT_MAPPER = new ObjectMapper();
    }

    private JacksonUtil() {
    }
    public static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }



    private static <T> T tryParse(Callable<T> parser) {
        return tryParse(parser, JacksonException.class);
    }

    private static <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        try {
            return parser.call();
        } catch (Exception var4) {
            if (check.isAssignableFrom(var4.getClass())) {
                throw new JsonParseException(var4);
            }
                throw new IllegalStateException(var4);
        }
    }

    /**
     * 将对象转换为json字符串
     * @param value
     * @return
     */
    public static String writeValueAsString(Object value) {
        return tryParse(() -> JacksonUtil.getObjectMapper().writeValueAsString(value));
}


    /**
     * 将json字符串转换为对象
     * @param content
     * @param javaType
     * @return
     * @param <T>
     */
    public static <T> T readValue(String content, Class<T> javaType) {
        return tryParse(() -> JacksonUtil.getObjectMapper().readValue(content, javaType));
}

public static <T> T readListValue(String content, Class<?> valueType) {
    JavaType javaType = JacksonUtil.getObjectMapper().getTypeFactory()
            // 1:todo
            .constructParametricType(List.class, valueType);
return tryParse(() -> JacksonUtil.getObjectMapper().readValue(content, javaType));
    }


}
